// 基于 SnowLang Project (https://gitee.com/jcnc-org/snow) 的衍生作品
// 原始版权归属: Copyright © 2025 Ke Xu (Luke)
// 本实现版权归属: Copyright © 2025 Sany
// 遵循 Apache License 2.0 授权
package flow

import (
	"errors"
	"fmt"

	"gitee.com/xntk2381/cc/vm/module"
)

const PROGRAM_END = int(^uint(0) >> 1)

type RetCommand struct{}

func (RetCommand) Execute(parts []string, currentPC int, operandStack *module.OperandStack, localVariableStore *module.LocalVariableStore, callStack *module.CallStack) (int, error) {
	if callStack.IsEmpty() {
		return 0, errors.New("RET: call stack is empty.")
	}

	topFrame, err := callStack.PeekFrame()
	if err != nil {
		return 0, err
	}

	// ----- Root frame: do NOT pop, just end program -----
	if topFrame.GetReturnAddress() == PROGRAM_END {
		fmt.Println("Return <root>")
		return PROGRAM_END, nil
	}

	// ----- Normal frame: pop & clean locals, then resume caller -----
	finished, err := callStack.PopFrame()
	if err != nil {
		return 0, err
	}
	finished.GetLocalVariableStore().ClearVariables()

	returnAddr := finished.GetReturnAddress()
	fmt.Println("Return ", returnAddr)
	return returnAddr, nil
}
